{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Incorporating Neural Networks\n",
    "\n",
    "author: Jacob Schreiber <br>\n",
    "contact: jmschreiber91@gmail.com\n",
    "\n",
    "Neural networks have become exceedingly popular recently due, in part, to their ability to achieve state-of-the-art performance on a variety of tasks without requiring complicated feature extraction pipelines. These models are frequently applied to domains where there is a great deal of raw structured data, such as computer vision, where neighboring pixels are strongly correlated, and natural language processing, where words are organized and modified in specific ways to convey meaning.\n",
    "\n",
    "There have been mergers between neural networks and probabilistic models. For example, deep hidden Markov models (DHMMs) are models where the input to the neural network is some observation, such as an image, and the output is the state in the hidden Markov model that the observation belongs to. These resulting probabilities are then treated as the likelihood function P(D|M) by the model, regularized using the transition matrix, and then re-normalized to get the posterior probabilities. Another example is a deep mixture model, where expectation-maximization is used to train the model on unlabeled samples.\n",
    "\n",
    "Thus far, pomegranate has stuck to probabilistic models that are not coupled with a neural network. However, with the recent inclusion of custom distributions, one can use a quick hack in order to turn pomegranate's models into deep models."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Fri Feb 15 2019 \n",
      "\n",
      "numpy 1.15.1\n",
      "scipy 1.1.0\n",
      "pomegranate 0.10.0\n",
      "\n",
      "compiler   : GCC 7.2.0\n",
      "system     : Linux\n",
      "release    : 4.15.0-45-generic\n",
      "machine    : x86_64\n",
      "processor  : x86_64\n",
      "CPU cores  : 4\n",
      "interpreter: 64bit\n"
     ]
    }
   ],
   "source": [
    "%matplotlib inline\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy\n",
    "import seaborn; seaborn.set_style('whitegrid')\n",
    "\n",
    "from pomegranate import *\n",
    "\n",
    "numpy.random.seed(0)\n",
    "\n",
    "%load_ext watermark\n",
    "%watermark -m -n -p numpy,scipy,pomegranate"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### What?\n",
    "\n",
    "Two natural questions emerge when considering the notion of combining a neural network and a probabilistic model. The first is: what is the benefit? The second: how does one do that?\n",
    "\n",
    "There are many benefits of merging a neural network and a probabilistic model. The simplest is that one can expand the expressiveness of probabilistic models by incorporating a neural network. Instead of forcing your data to come neatly in the form of a single distribution or a mixture of distributions, one can process data that comes in more structured forms such as images. Additionally, a neural network may be able to extract more complicated relationships amongst the features of existing data sets than a simple covariance matrix could.\n",
    "\n",
    "Practically, this works by having a single neural network replace the entire set of distributions in your model where the model has the same number of outputs as probability distributions that used to be in your model. For example, a HMM that has eight states would be coupled with a neural network that makes predictions for eight classes. First, each observation in your sequence would be run through the neural network to get the predictions for each observation. This calculation is essentially the same as calculating the probability of an observation given each state and then normalizing, i.e., taking a softmax. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The Neural Network Wrapper\n",
    "\n",
    "We can hack pomegranate models by using a custom distribution that wraps our neural network (using the package of your choice). The following class will store a pointer to your model, an identifying of which class it's representing, and train or make predictions using the given class. When asked for a log probability, it returns the posterior probability of the observation given the class it's storing. When training, it stores data and labels (it's own class ID) and then performs a single round of training to update. Note that this is the exact code that is already implemented in pomegranate, except this version is called \"NeuralNetworkWrapperExample\" instead of \"NeuralNetworkWrapper\", and is only shown here for reference as to what's going on in the backend."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "class NeuralNetworkWrapperExample():\n",
    "    '''A wrapper for a neural network model for use in pomegranate.\n",
    "    \n",
    "    This wrapper will store a pointer to the model, as well as an indicator\n",
    "    of what class it represents. It needs information about the number of\n",
    "    dimensions of the input and the total number of classes in the input.\n",
    "    It is currently built to work with keras models, but can be easily\n",
    "    modified to work with the package of your choice.\n",
    "    \n",
    "    Training works in a somewhat hacky manner. Internally, pomegranate\n",
    "    will scan over all components of the model, calling `summarize` for each\n",
    "    one, and then `from_summaries` at the end. During the EM procedure, the\n",
    "    samples and their associated weights are passed in to the `summarize`\n",
    "    function. The associated weights are the responsibilities calculated\n",
    "    during the EM algorithm. In theory, one could simply update the model\n",
    "    using the samples and their corresponding weights. In practice, it's much\n",
    "    better to reconstruct the whole responsibility matrix for the batch of\n",
    "    data and then train on soft labels.\n",
    "    \n",
    "    The process for training is as follows. When pomegranate starts a round of\n",
    "    optimization, this wrapper will store a pointer to the data set to the\n",
    "    neural network model object. This data set is the same one passed to each\n",
    "    NeuralNetworkWrapper, the only difference being the ~weights~. Thus, each\n",
    "    successive call will store the weights that are passed in (the responsibilities\n",
    "    from the EM algorithm) to an associated label matrix. The result is a single\n",
    "    copy of the data batch and a corresponding matrix of soft labels. Keras\n",
    "    allows us to train a classifier on soft labels, and this is the preferred\n",
    "    strategy.\n",
    "    \n",
    "    Parameters\n",
    "    ----------\n",
    "    model : object\n",
    "        The neural network model being utilized.\n",
    "        \n",
    "    i : int\n",
    "        The class that this distribution represents.\n",
    "    \n",
    "    n_dimensions : int\n",
    "        The number of dimensions in the input.\n",
    "    \n",
    "    n_classes : int\n",
    "        The total number of classes that the model can output.\n",
    "    '''\n",
    "    \n",
    "    def __init__(self, model, i, n_dimensions, n_classes):\n",
    "        self.d = n_dimensions\n",
    "        self.n_classes = n_classes\n",
    "        self.model = model\n",
    "        self.i = i\n",
    "        self.model.X = []\n",
    "        self.model.y = []\n",
    "        self.model.w = []\n",
    "    \n",
    "    def log_probability(self, X):\n",
    "        ''' Return pseudo-log probabilities from the neural network.\n",
    "        \n",
    "        This method returns the log probability of the class that this\n",
    "        wrapper represents given the model. Thus, it's not strictly a\n",
    "        likelihood function, but rather, a posterior. However, because\n",
    "        the HMM takes log probabilities, multiplies them with a prior,\n",
    "        and then normalizes them, mathematically they work out to be\n",
    "        equivalent.\n",
    "\n",
    "        This method uses the `predict` function from the neural network,\n",
    "        which should take in a single batch of data, and returns the\n",
    "        posterior probability of each class given the network. Typically,\n",
    "        this is calculated using a softmax function on the outputs. The\n",
    "        output of this function should be a matrix of size (n, k), where\n",
    "        n is the number of samples and k is the number of classes, where\n",
    "        the sum over each sample is equal to 1. \n",
    "\n",
    "        Parameters\n",
    "        ----------\n",
    "        X : numpy.ndarray, shape=(n, d)\n",
    "            The batch of data to calculcate probabilities over.\n",
    "        '''\n",
    "        \n",
    "        return numpy.log(self.model.predict(X)[:,self.i])\n",
    "    \n",
    "    def summarize(self, X, w):\n",
    "        '''When shown a batch of data, store the data.\n",
    "\n",
    "        This will store the batch of data, and associated weights, to the\n",
    "        object. The actual update occurs when `from_summaries` is called.\n",
    "\n",
    "        Parameters\n",
    "        ----------\n",
    "        X : numpy.ndarray, shape=(n, d)\n",
    "            The batch of data to be passed in.\n",
    "\n",
    "        w : numpy.ndarray, shape=(n,)\n",
    "            The associated weights. These can be uniform if unweighted.\n",
    "\n",
    "        Returns\n",
    "        -------\n",
    "        None\n",
    "        '''\n",
    "\n",
    "        if self.i == 0:\n",
    "            self.model.X = X.copy()\n",
    "            self.model.y = numpy.zeros((X.shape[0], self.n_classes))\n",
    "            \n",
    "        self.model.y[:, self.i] = w\n",
    "        \n",
    "    def from_summaries(self, inertia=0.0):\n",
    "        '''Perform a single gradient update to the network.\n",
    "\n",
    "        This will perform a single gradient update step, using the\n",
    "        `train_on_batch` method from the network. This is already implemented\n",
    "        for keras networks, but for other networks this method will have to\n",
    "        be implemented. It should take in a single batch of data, along with\n",
    "        associated sample weights, and update the model weights.\n",
    "\n",
    "        Parameters\n",
    "        ----------\n",
    "        inertia : double, optional\n",
    "            This parameter is ignored for neural networks, but required for\n",
    "            compatibility reasons.\n",
    "\n",
    "        Returns\n",
    "        -------\n",
    "        None\n",
    "        '''\n",
    "\n",
    "\n",
    "        if self.i == 0:\n",
    "            self.model.train_on_batch(self.model.X, self.model.y)\n",
    "            self.clear_summaries()\n",
    "    \n",
    "    def clear_summaries(self):\n",
    "        self.model.X = None\n",
    "        self.model.y = None\n",
    "\n",
    "\n",
    "    @classmethod\n",
    "    def from_samples(self, X, weights):\n",
    "        '''The training of this wrapper on data should be performed in the main model.\n",
    "\n",
    "        This method should not be used directly to train the network.\n",
    "        '''\n",
    "\n",
    "        return self\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Deep mixture models"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first model we'll merge with a deep network is the general mixture model. Here, our neural network model can have any architecture as long as it outputs a number of classes equal to the number of components that you'd like in the mixture model. Our goal is to then train the neural network in an unsupervised manner using EM. This can be very difficult to do correctly and fragile, so use with care.\n",
    "\n",
    "Let's demonstrate this on the MNIST handwritten digits data set, where we want to learn a model that can distinguish 2's from 9's without any training labels. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using Theano backend.\n"
     ]
    }
   ],
   "source": [
    "from keras.datasets import mnist\n",
    "\n",
    "(X_train, y_train), (X_test, y_test) = mnist.load_data()\n",
    "\n",
    "X_train = X_train[(y_train == 2) | (y_train == 9)]\n",
    "X_test = X_test[(y_test == 2) | (y_test == 9)]\n",
    "y_test = y_test[(y_test == 2) | (y_test == 9)]\n",
    "\n",
    "n, d = X_train.shape[0], 784\n",
    "\n",
    "X_train = X_train.reshape(n, d)\n",
    "X_test = X_test.reshape(X_test.shape[0], d)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, we have to implement the initialization step by hand because it's currently not built-in. First we use K-means to cluster the data and assign preliminary labels. Then, we train our neural network model for some amount of time on those labels. Lastly, we use EM to refine our labels just in case the initial K-means cluster was not good enough. This procedure is essentially identical to the built-in initialization for mixtures, with the only difference being that all the complexities of training a neural network replace the simplicity of fitting a probability distribution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.cluster import KMeans\n",
    "from pomegranate import GeneralMixtureModel\n",
    "from pomegranate import NeuralNetworkWrapper\n",
    "\n",
    "from keras.layers import Dense\n",
    "from keras.models import Sequential\n",
    "\n",
    "numpy.random.seed(111)\n",
    "\n",
    "# Use k-means to get an initial clustering of our data\n",
    "y_init = KMeans(2).fit_predict(X_train)\n",
    "y_kmeans = numpy.zeros((n, 2))\n",
    "y_kmeans[numpy.arange(n), y_init] = 1\n",
    "\n",
    "# Define the neural network model. Here we use a simple model for illustration. \n",
    "nn = Sequential([\n",
    "    Dense(128, input_dim=d, activation='relu'), \n",
    "    Dense(2, activation='softmax')\n",
    "])\n",
    "\n",
    "nn.compile(loss='categorical_crossentropy', optimizer='adam')\n",
    "\n",
    "# Now we fit to the k-means defined labels. \n",
    "nn.fit(X_train, y_kmeans, epochs=10, verbose=False)\n",
    "\n",
    "# Here we define our wrappers---one for each component in our mixture / each class in our neural model\n",
    "d1 = NeuralNetworkWrapper(nn, 0, d, 2)\n",
    "d2 = NeuralNetworkWrapper(nn, 1, d, 2)\n",
    "\n",
    "# We feed the wrapper into the mixture model as you would a normal distribution\n",
    "model1 = GeneralMixtureModel([d1, d2])\n",
    "\n",
    "# Now we fit the model using EM, just as one would with built-in distributions\n",
    "model1.fit(X_train, max_iterations=10, stop_threshold=0.1)\n",
    "\n",
    "# And make predictions just as one would with normal distributions\n",
    "y_hat = model1.predict(X_test)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's take a look at the clusters that are found using this approach."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAsgAAACpCAYAAAA2nMugAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDIuMi4zLCBodHRwOi8vbWF0cGxvdGxpYi5vcmcvIxREBQAAIABJREFUeJzt3XmczdUfx/HXvXdmjBnGLjshkp2sWYuios0ShRSlEGXLFil+1iyRJVSUIkqSokRIEVkqS/Z938aY/d77++PMjDvMZ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REXKhAFhERERFxoQJZRERERMSFCmQRERERERcqkEVEREREXKhAFhERERFxoQJZRERERMSFCmQRERERERcqkEVEREREXKhAFhERERFxoQJZRERERMSFCmQRERERERcqkEVEREREXKhAFhERERFxoQJZRERERMSFCmQRERERERcqkEVEREREXKhAFhERERFxoQJZRERERMSFCmQRERERERcqkEVEREREXKhAFhERERFxoQJZRERERMSFCmQRERERERcqkEVEREREXKhAFhERERFxoQJZRERERMSFCmQRERERERcqkEVEREREXKhAFhERERFxoQJZRERERMSFCmQRERERERcqkEVEREREXKhAFhERERFxoQJZRERERMSFCmQRERERERcqkEVEREREXKhAFhERERFxoQJZRERERMSFCmQRERERERcqkEVEREREXKhAFhERERFxoQJZRERERMSFCmQRERERERcqkEVEREREXKhAFhERERFxoQJZRERERMSFCmQRERERERcqkEVEREREXKhAFhERERFxoQJZRERERMSFCmQRERERERcqkEVEREREXKhAFhERERFxoQJZRERERMSFCmQRERERERcqkEVEREREXKhAFhERERFxoQJZRERERMSFCmQRERERERd+Gfrbwi85M/T3pUVQNou7QwCUm5QoN8lTbpKn3CRPuUma8pI85SZ5yk3yvDg3GkEWEREREXGhAllERERExIUKZBERERERFyqQRURERERcqEAWEREREXGhAllERERExIUKZBERERERFyqQxafZf1vMlTZNmHFXCboEF6JLcCF+KlqG2LdfcndoHsl55jARLzZnQ/FybCheDsfeLe4OSTxEeIfHCe/wOK8GF+bnomU4VLM6a4qVZU2xskS82Bz7nJE4zx83/zkc7g7XLRx7NhParCE/FrmXH4vcS5+QIkzLW4JXgwvzanBhugQXIrLzk+4OUzycfeUXrCp6X8JnVmzf5+7Yv6l4zthonLHRxL7bhSHZi/FZ/pJ8lr8k/bMVxf7nj1ePO3OY2MEv4nQ4bjlnFqczA9dwvg0LRjuO78F58hAAMdOm8MeK3Vgxaz4/MLg1liaUApD/AAAXy0lEQVTPYi1YKu0n9JHFtO07f2fPs135YO8ZcxsnNiwMqFQAgPxffYYlZwEcv8wHwNqoDZaAzCmf1Etz47x4inWV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C1SBn3BeZGzounaPq/F7G27Z36wRnA4nTe8jbZaXeDe3LH/q8b3d4zsxknD2uFX6/3b39MPrRfuf2T4awb+jkAdeaNxFb7Flex8KHc3HbKTfJ8KDf2P39kYyvzZl195kBsD7W5tRP6UG5uO0/IjfKSPOUmecpN8rw4N+pBFhERERFx4dEjyBlC37KSp9wkT7lJnnKTPOUmeZ6QG+UlecpN8pSb5HlxbjK2QBYRERER8XBqsRARERERcaECWURERETEhQpkEREREREXKpBFRERERFyoQBYRERERcaECWURERETEhQpkEREREREXKpBFRERERFyoQBYRERERcaECWURERETEhQpkEREREREXKpBFRERERFyoQBYRERERcaECWURERETEhQpkEREREREXKpBFRERERFyoQBYRERERcaECWURERETEhQpkEREREREXKpBFRERERFyoQBYRERERcaECWURERETEhQpkEREREREX/wfxELRey70a1gAAAABJRU5ErkJggg==\n",
      "text/plain": [
       "<Figure size 720x216 with 20 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "plt.figure(figsize=(10, 3))\n",
    "\n",
    "X_test_r = X_test.reshape(X_test.shape[0], 28, 28)\n",
    "\n",
    "for i in range(1, 11):\n",
    "    plt.subplot(2, 10, i)\n",
    "    plt.imshow(X_test_r[y_hat == 0][i], cmap='Greens')\n",
    "    plt.axis('off')\n",
    "    \n",
    "    plt.subplot(2, 10, i+10)\n",
    "    plt.imshow(X_test_r[y_hat == 1][i], cmap='Reds')\n",
    "    plt.axis('off')\n",
    "\n",
    "plt.tight_layout()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Looks good! One cluster clearly seems to be 2's, and one clearly appears to be 9's. \n",
    "\n",
    "But, how much of this was just because K-means did a good job of clustering MNIST, which is a notoriously easy data set? Well, we can evaluate that by seeing how good the predictions using K-means would be versus our deep mixture model. Let's print out the accuracy using the predicted labels, and those labels flipped, just because we don't know which cluster ends up corresponding to which original label when you use unsupervised methods for training."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('kmeans: ', 0.9608035276825085, 0.039196472317491425)\n",
      "('deep mixture model: ', 0.9696227339539442, 0.030377266046055854)\n"
     ]
    }
   ],
   "source": [
    "y_kmeans_hat = KMeans(2).fit(X_train).predict(X_test)\n",
    "\n",
    "y_test[y_test == 2] = 0\n",
    "y_test[y_test == 9] = 1\n",
    "\n",
    "print(\"kmeans: \", (y_kmeans_hat == y_test).mean(), ((1 - y_kmeans_hat) == y_test).mean())\n",
    "print(\"deep mixture model: \", (y_hat == y_test).mean(), ((1 - y_hat) == y_test).mean())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It looks like we get a small improvement in performance. Now, MNIST is notoriously easy and one could likely get much better performance by tuning the K-means model. However, this does demonstrate that deep mixture models have potential for much larger and more complicated phenomena."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Deep hidden Markov models\n",
    "\n",
    "The next type of model we could merge with a neural network is a hidden Markov model. In this situation, the classes in the neural network correspond to hidden states in the HMM, and the edges in the HMM correspond to probabilistic constraints in the network predictions over a sequence.\n",
    "\n",
    "To demonstrate how this would work we consider the situation in which one has a pre-trained object recognition network and wants to adapt it to work over videos (sequences of images) but doesn't have labels for each frame in their data. The goal is not to refine the network, which has been pre-trained, but to train the HMM such that it learns a useful transition matrix to constrain the predictions from the neural network alone applied to each frame sequentially.\n",
    "\n",
    "Let's use the MNIST data set again, but this time use data from each of the 10 classes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from keras.utils import to_categorical\n",
    "\n",
    "(X_train, y_train), (X_test, y_test) = mnist.load_data()\n",
    "\n",
    "X_train = X_train.reshape(X_train.shape[0], X_train.shape[1] * X_train.shape[2])\n",
    "y_train_ohe = to_categorical(y_train, num_classes=10)\n",
    "\n",
    "X_test = X_test.reshape(X_test.shape[0], X_test.shape[1] * X_test.shape[2])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Because keras doesn't have any pre-trained MNIST models, let's pre-train some simple model on the training set and then freeze it. We use L2 regularization because unregularized dense networks with lots of parameters have a tendancy to predict probabilities of 1 rather than smooth probability distributions. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "from keras.regularizers import l2\n",
    "\n",
    "# Define our neural network model. In this case it's a small dense network for fast training, but in\n",
    "# practice it can be anything that has 10 classes as the output.\n",
    "nn = Sequential([\n",
    "    Dense(32, activation='relu', input_dim=784, kernel_regularizer=l2(1.)),\n",
    "    Dense(10, activation='softmax')\n",
    "])\n",
    "\n",
    "nn.compile(loss='categorical_crossentropy', optimizer='adam')\n",
    "\n",
    "# Now we fit our model to the data to get a \"pre-trained\" model\n",
    "nn.fit(X_train, y_train_ohe, epochs=25, verbose=False, batch_size=256)\n",
    "\n",
    "# After training we go through and freeze the model so that training our HMM later on doesn't affect the parameters\n",
    "for layer in nn.layers:\n",
    "    layer.trainable = False\n",
    "\n",
    "nn.compile(loss='categorical_crossentropy', optimizer='adam')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we have to generate sequences from our training data of images. Our \"videos\" will be sequences of images, and we add structure by enforcing that the images are of digits that either stay the same value or increase. For example, a \"video\" might be images of the digits 1, 1, 2, and 5 sequentially, but not 1, 4, and 2 sequentially. Our goal is to train the HMM to learn this constraint.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "def generate_videos(X_train, y_train, n=1000):\n",
    "    seqs, labels = [], []\n",
    "    \n",
    "    for _ in range(n):\n",
    "        seq, label, number = [], [], 0\n",
    "        \n",
    "        # Our videos can be a maximum of 25 images\n",
    "        for i in range(25):\n",
    "            chance = numpy.random.choice(4)\n",
    "            \n",
    "            # There's a 25% chance that the next image skips a number, but only as long as it\n",
    "            # stays between 1 and 10, e.g. 1 followed by a 3. \n",
    "            if chance == 2:\n",
    "                if number < 8:\n",
    "                    number += 2\n",
    "                \n",
    "            # There's a 25% chance that the next image proceeds to the next number, e.g. 1 followed by a 2\n",
    "            elif chance == 3:\n",
    "                if number < 9:\n",
    "                    number += 1\n",
    "            \n",
    "            # There's a 50% chance that the next image is of the same number, e.g. 1 followed by a 1\n",
    "            \n",
    "            # If we've seen at least one image already, there's an independent 10% chance that\n",
    "            # the sequence terminates to give us a distribution of sequence lengths\n",
    "            if i > 1 and numpy.random.choice(10) == 9:\n",
    "                break\n",
    "            \n",
    "            idx = numpy.random.randint((y_train == number).sum())\n",
    "            seq.append(X_train[y_train == number][idx])\n",
    "            label.append(number)\n",
    "        \n",
    "        labels.append(label)\n",
    "        seqs.append(numpy.array(seq))\n",
    "    \n",
    "    return seqs, labels\n",
    "\n",
    "X_train_seqs, y_train_seqs = generate_videos(X_train, y_train, 1000)\n",
    "X_test_seqs, y_test_seqs = generate_videos(X_test, y_test, 100)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, let's hand define a model where you can either stay in the same hidden state of proceed to any of the next three states. In this case, a state corresponds to a number / class in the MNIST data set. If one doesn't have prior knowledge of what the transition structure should look like they can train the model similarly to the deep mixture model example above. However, this will allow us to see whether training the model using EM actually works to improve on rough hand-specified constraints."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "d0 = NeuralNetworkWrapper(nn, 0, 28*28, 10)\n",
    "d1 = NeuralNetworkWrapper(nn, 1, 28*28, 10)\n",
    "d2 = NeuralNetworkWrapper(nn, 2, 28*28, 10)\n",
    "d3 = NeuralNetworkWrapper(nn, 3, 28*28, 10)\n",
    "d4 = NeuralNetworkWrapper(nn, 4, 28*28, 10)\n",
    "d5 = NeuralNetworkWrapper(nn, 5, 28*28, 10)\n",
    "d6 = NeuralNetworkWrapper(nn, 6, 28*28, 10)\n",
    "d7 = NeuralNetworkWrapper(nn, 7, 28*28, 10)\n",
    "d8 = NeuralNetworkWrapper(nn, 8, 28*28, 10)\n",
    "d9 = NeuralNetworkWrapper(nn, 9, 28*28, 10)\n",
    "\n",
    "s0 = State(d0, \"s0\")\n",
    "s1 = State(d1, \"s1\")\n",
    "s2 = State(d2, \"s2\")\n",
    "s3 = State(d3, \"s3\")\n",
    "s4 = State(d4, \"s4\")\n",
    "s5 = State(d5, \"s5\")\n",
    "s6 = State(d6, \"s6\")\n",
    "s7 = State(d7, \"s7\")\n",
    "s8 = State(d8, \"s8\")\n",
    "s9 = State(d9, \"s9\")\n",
    "\n",
    "model = HiddenMarkovModel()\n",
    "model.add_states(s0, s1, s2, s3, s4, s5, s6, s7, s8, s9)\n",
    "model.add_transition(model.start, s0, 0.33)\n",
    "model.add_transition(model.start, s1, 0.33)\n",
    "model.add_transition(model.start, s2, 0.34)\n",
    "\n",
    "model.add_transition(s0, s0, 0.24)\n",
    "model.add_transition(s0, s1, 0.24)\n",
    "model.add_transition(s0, s2, 0.24)\n",
    "model.add_transition(s0, s3, 0.24)\n",
    "model.add_transition(s0, model.end, 0.04)\n",
    "\n",
    "model.add_transition(s1, s1, 0.24)\n",
    "model.add_transition(s1, s2, 0.24)\n",
    "model.add_transition(s1, s3, 0.24)\n",
    "model.add_transition(s1, s4, 0.24)\n",
    "model.add_transition(s1, model.end, 0.04)\n",
    "\n",
    "model.add_transition(s2, s2, 0.24)\n",
    "model.add_transition(s2, s3, 0.24)\n",
    "model.add_transition(s2, s4, 0.24)\n",
    "model.add_transition(s2, s5, 0.24)\n",
    "model.add_transition(s2, model.end, 0.04)\n",
    "                    \n",
    "model.add_transition(s3, s3, 0.24)\n",
    "model.add_transition(s3, s4, 0.24)\n",
    "model.add_transition(s3, s5, 0.24)\n",
    "model.add_transition(s3, s6, 0.24)\n",
    "model.add_transition(s3, model.end, 0.04)\n",
    "\n",
    "model.add_transition(s4, s4, 0.24)\n",
    "model.add_transition(s4, s5, 0.24)\n",
    "model.add_transition(s4, s6, 0.24)\n",
    "model.add_transition(s4, s7, 0.24)\n",
    "model.add_transition(s4, model.end, 0.04)\n",
    "\n",
    "model.add_transition(s5, s5, 0.24)\n",
    "model.add_transition(s5, s6, 0.24)\n",
    "model.add_transition(s5, s7, 0.24)\n",
    "model.add_transition(s5, s8, 0.24)\n",
    "model.add_transition(s5, model.end, 0.04)\n",
    "\n",
    "model.add_transition(s6, s6, 0.24)\n",
    "model.add_transition(s6, s7, 0.24)\n",
    "model.add_transition(s6, s8, 0.24)\n",
    "model.add_transition(s6, s9, 0.24)\n",
    "model.add_transition(s6, model.end, 0.04)\n",
    "\n",
    "model.add_transition(s7, s7, 0.25)\n",
    "model.add_transition(s7, s8, 0.25)\n",
    "model.add_transition(s7, s9, 0.25)\n",
    "model.add_transition(s7, model.end, 0.25)\n",
    "\n",
    "model.add_transition(s8, s8, 0.33)\n",
    "model.add_transition(s8, s9, 0.33)\n",
    "model.add_transition(s8, model.end, 0.34)\n",
    "\n",
    "model.add_transition(s9, s9, 0.5)\n",
    "model.add_transition(s9, model.end, 0.5)\n",
    "model.bake()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can make predictions using the maximum a posteriori (MAP) algorithm."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "y_pred = numpy.concatenate([model.predict(seq) for seq in X_test_seqs])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Alternately, we could apply our pre-trained model to each image individually to make predictions. If our deep HMM model does not outperform this, there is no benefit to combining the neural network with a probabilistic model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "y_nn_pred = numpy.argmax(nn.predict(numpy.concatenate(X_test_seqs)), axis=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's evaluate our models using simple accuracy at predicting the value of each image."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('pre-trained model: ', 0.9231464737793852)\n",
      "('deep HMM before training: ', 0.9792043399638336)\n"
     ]
    }
   ],
   "source": [
    "y_true = numpy.concatenate(y_test_seqs)\n",
    "\n",
    "print(\"pre-trained model: \", (y_nn_pred == y_true).mean())\n",
    "print(\"deep HMM before training: \", (y_pred == y_true).mean())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It looks like there is a significant improvement using the HMM, even before refinement of the transition matrix using EM. This is because there are predictions that the pre-trained neural network alone may have gotten incorrect, but when combined with the transition matrix the correct label became more likely. For example, there may be a situation where the model alone thought that a 0 came after a 3. However, our transition matrix says that that is impossible. Essentially, our HMM allows our model to consider context better. \n",
    "\n",
    "Now, what happens when we train the model? Remember that we froze our model, so this refinement is only done on the transition matrix of the HMM, not the parameters of the pre-trained neural network."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1] Improvement: 3167.82880474\tTime (s): 7.191\n",
      "[2] Improvement: 46.46103046\tTime (s): 7.029\n",
      "[3] Improvement: 5.49539624626\tTime (s): 7.207\n",
      "[4] Improvement: 1.37985857847\tTime (s): 7.154\n",
      "[5] Improvement: 0.488223125971\tTime (s): 7.188\n",
      "[6] Improvement: 0.211493207351\tTime (s): 7.188\n",
      "[7] Improvement: 0.103808710392\tTime (s): 7.27\n",
      "[8] Improvement: 0.0552500054655\tTime (s): 7.145\n",
      "[9] Improvement: 0.0311245813919\tTime (s): 7.147\n",
      "[10] Improvement: 0.018309211895\tTime (s): 7.189\n",
      "Total Training Improvement: 3222.07329887\n",
      "Total Training Time (s): 78.8414\n"
     ]
    }
   ],
   "source": [
    "_ = model.fit(X_train_seqs, max_iterations=10, verbose=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('pre-trained model: ', 0.9231464737793852)\n",
      "('deep HMM before training: ', 0.9792043399638336)\n",
      "('deep HMM after training: ', 0.9855334538878843)\n"
     ]
    }
   ],
   "source": [
    "y_pred2 = numpy.concatenate([model.predict(seq) for seq in X_test_seqs])\n",
    "\n",
    "print(\"pre-trained model: \", (y_nn_pred == y_true).mean())\n",
    "print(\"deep HMM before training: \", (y_pred == y_true).mean())\n",
    "print(\"deep HMM after training: \", (y_pred2 == y_true).mean())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It looks like the addition of the constraints by themselves leads to a large improvement in performance, and that refining the transition matrix leads to further improvements. \n",
    "\n",
    "Even if we don't know the structure of the HMM beforehand we can still get good performance."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1] Improvement: 11385.6094235\tTime (s): 6.5\n",
      "[2] Improvement: 1495.15851959\tTime (s): 6.434\n",
      "[3] Improvement: 221.541352097\tTime (s): 6.438\n",
      "[4] Improvement: 36.4806422466\tTime (s): 6.501\n",
      "[5] Improvement: 8.603361119\tTime (s): 6.425\n",
      "[6] Improvement: 2.28461893309\tTime (s): 6.604\n",
      "[7] Improvement: 0.693117308972\tTime (s): 6.444\n",
      "[8] Improvement: 0.281554052133\tTime (s): 6.427\n",
      "[9] Improvement: 0.140599682802\tTime (s): 6.488\n",
      "[10] Improvement: 0.0812708375324\tTime (s): 6.431\n",
      "Total Training Improvement: 13150.8744594\n",
      "Total Training Time (s): 71.1533\n",
      "('pre-trained model: ', 0.918625678119349)\n",
      "('deep HMM before training: ', 0.9819168173598554)\n"
     ]
    }
   ],
   "source": [
    "nn = Sequential([\n",
    "    Dense(32, activation='relu', input_dim=784, kernel_regularizer=l2(1.)),\n",
    "    Dense(10, activation='softmax')\n",
    "])\n",
    "\n",
    "nn.compile(loss='categorical_crossentropy', optimizer='adam')\n",
    "\n",
    "nn.fit(X_train, y_train_ohe, epochs=25, verbose=False, batch_size=256)\n",
    "\n",
    "for layer in nn.layers:\n",
    "    layer.trainable = False\n",
    "\n",
    "nn.compile(loss='categorical_crossentropy', optimizer='adam')\n",
    "y_nn_pred = numpy.argmax(nn.predict(numpy.concatenate(X_test_seqs)), axis=1)\n",
    "\n",
    "distributions = [NeuralNetworkWrapper(nn, i, 28*28, 10) for i in range(10)]\n",
    "\n",
    "model = HiddenMarkovModel.from_samples(distributions, 10, X_train_seqs, max_iterations=10, verbose=True)\n",
    "y_pred = numpy.concatenate([model.predict(seq) for seq in X_test_seqs])\n",
    "\n",
    "print(\"pre-trained model: \", (y_nn_pred == y_true).mean())\n",
    "print(\"deep HMM before training: \", (y_pred == y_true).mean())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In a situation where one has labels for all images in a sequence, a recurrent neural network is likely to have superior performance to a HMM at this type of classification. However, when one doesn't have class labels, deep HMMs can be a very powerful tool."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
